﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Viettel.VOFFICE.DAO.DAL;
using Viettel.VOFFICE.DAO.Enums;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class FileController : Controller
    {
        /// <summary>
        /// Hàm upload file từ client sử dụng qqUploader
        /// </summary>
        /// <param name="qqfile"></param>
        /// <param name="folder"></param>
        /// <returns>Trả về đường dẫn tương đối</returns>
        [HttpPost]
        [ActionName("upload")]
        public JsonResult Upload(string qqfile, string folder = "")
        {
            try
            {
                List<ValidationResult> outError;
                var path = RootFoler + folder;
                var di = new DirectoryInfo(path);
                if (!di.Exists)
                {
                    di.Create();
                }
                string fileName;
                var stream = Request.InputStream;
                var guid = Guid.NewGuid();
                string file;
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    if (null == postedFile) return Json(new { success = false, message = @Resources.Resources.FileUploadedFail }, "text/html");
                    stream = postedFile.InputStream;
                    qqfile = Path.GetFileName(postedFile.FileName);
                    fileName = string.Format(@"{0}{1}", guid.ToString(), Path.GetExtension(postedFile.FileName));
                    file = Path.Combine(path, fileName);
                }
                else
                {
                    //Webkit, Mozilla
                    fileName = string.Format(@"{0}{1}", guid.ToString(), qqfile.GetFileExtension());
                    file = Path.Combine(path, fileName);
                }
                var fileModel = new UploadFileModel()
                    {
                        FileContent = stream,
                        FilePath = file,
                        FileName = fileName
                    };
                if (fileModel.IsValid(out outError))
                {
                    var buffer = new byte[fileModel.FileContent.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    System.IO.File.WriteAllBytes(fileModel.FilePath, buffer);
                    return Json(new { success = true, path = folder + fileName, name = qqfile }, "text/html");
                }
                return Json(new { success = false, message = string.Join(", ", outError) }, "text/html");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, "text/html");
            }
        }

        /// <summary>
        /// Tải về file bằng đường dẫn tương đối
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DownloadByPath(string filePath)
        {
            return new DownloadResult(RootFoler + filePath, Path.GetFileName(filePath));
        }

        /// <summary>
        /// Tải về file bằng id của bản ghi trong db
        /// </summary>
        /// <param name="id">id của bản ghi  trong csdl</param>
        /// <param name="type">phân loại để xác định được nơi truy xuất file(bảng dữ liệu)</param>
        /// <param name="extension"></param>
        /// <returns></returns>
        public ActionResult DownloadById(int id, AttachmentType type, FileExtensionType extension = FileExtensionType.Default)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var item = unitOfWork.AttachmentRepository.GetByIdAndType(id, type);
                if (null != item)
                {
                    var dbUrl = item.FilePath;
                    switch (extension)
                    {
                        case FileExtensionType.Docx:
                            dbUrl = item.DocPath;
                            break;
                        case FileExtensionType.Pdf:
                            dbUrl = item.PdfPath;
                            break;
                        case FileExtensionType.Image:
                            dbUrl = item.ImgPath;
                            break;
                    }
                    if (!string.IsNullOrWhiteSpace(dbUrl))
                    {
                        return new DownloadResult(RootFoler + dbUrl, extension == FileExtensionType.Default ? item.FileName : Path.GetFileName(dbUrl));
                    }
                }
                return null;
            }
        }

        /// <summary>
        /// Download tệp từ thư viện
        /// </summary>
        /// <param name="id"></param>
        /// <param name="extension"></param>
        /// <returns></returns>
        public ActionResult DownloadFromLibrary(int id, FileExtensionType extension = FileExtensionType.Default)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var item = unitOfWork.LibraryRepository.GetById(id);
                if (null != item)
                {
                    var dbUrl = item.AttachmentPath;
                    switch (extension)
                    {
                        case FileExtensionType.Docx:
                            dbUrl = item.AttachmentDocPath;
                            break;
                        case FileExtensionType.Pdf:
                            dbUrl = item.AttachmentPdfPath;
                            break;
                        case FileExtensionType.Image:
                            dbUrl = item.AttachmentImagePath;
                            break;
                    }
                    if (!string.IsNullOrWhiteSpace(dbUrl))
                    {
                        return new DownloadResult(RootFoler + dbUrl, extension == FileExtensionType.Default ? item.AttachmentName : Path.GetFileName(dbUrl));
                    }
                }
                return null;
            }
        }

        /// <summary>
        /// Lấy ra folder mặc định từ webconfig để tạo ra các đường dẫn download file
        /// </summary>
        protected string RootFoler
        {
            get
            {
                var rootFoler = ConfigurationManager.AppSettings["WebUploadRootFolder"];
                if (string.IsNullOrWhiteSpace(rootFoler))
                {
                    throw new Exception("Can not find root folder.");
                }
                return rootFoler;
            }
        }
    }
}


